from django.shortcuts import render, redirect

from la import models
from la.views import SkuInfoModelForm


def skuinfo(req):
    """SKU列表"""
    skuinfos = models.skuinfo.objects.all()
    return render(req, "skuinfo.html", {"skuinfo": skuinfos})


def skuinfo_add(req):
    """SKU添加"""
    if req.method == "GET":
        form = SkuInfoModelForm()
        return render(req, "skuinfo_add.html", {"form": form})
    form = SkuInfoModelForm(data = req.POST)
    if addSku(form):
        return redirect("/la/skuinfo/")
    else:
        return render(req, "skuinfo_add.html", {"form": form})


def addSku(skuinfo):
    if skuinfo.is_valid():
        skuinfo.save()
        return True
    return False


def skuinfo_edit(req, nid):
    """SKU修改"""
    skuinfo = models.skuinfo.objects.filter(id = nid).first()
    if req.method == "GET":
        form = SkuInfoModelForm(instance = skuinfo)
        return render(req, "skuinfo_edit.html", {"form": form})
    form = SkuInfoModelForm(data = req.POST, instance = skuinfo)
    if form.is_valid():
        form.save()
        return redirect("/la/skuinfo/")
    else:
        return render(req, "skuinfo_edit.html", {"form": form})


def uploadSKU(req):
    if req.method == "GET":
        brand = models.brandlist.objects.all()
        return render(req, "uploadSKU.html", {"brand": brand})
    if req.method == "POST":
        skufile = req.FILES.get("sku")
        brand = req.POST.get("brand")
        from openpyxl import load_workbook
        if skufile:
            skufile = load_workbook(skufile)
            if skufile.active.max_column == 10:
                print("列数正确")
                if skufile.active['A1'].value == "款号" and skufile.active['J1'].value == '成本':
                    print("标题正确")
                    for row in skufile.active.iter_rows(2):
                        re = models.skuinfo.objects.filter(sku = row[0].value).first()
                        if re:
                            continue
                        models.skuinfo.objects.create(sku = row[0].value,
                                                      year = row[1].value,
                                                      season = row[2].value,
                                                      wave = row[3].value, color = row[4].value,
                                                      colorCode = row[5].value,
                                                      size = row[6].value, type = row[7].value,
                                                      price = row[8].value, cost = row[9].value, brand_id = brand)
                        print("成功写入:" + str(row[0].value))
        return render(req, "uploadSKU.html", {"brand": brand})
